package com.example.redis.dao.base;

import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * Redis基础DAO
 * <p>Title:RedisGeneratorDao</p>
 * <p>Company: jiantong</p>
 * @author sunbing
 * @date 2017年12月13日 上午10:41:47
 * @param <K>
 * @param <V>
 */
public abstract class RedisGeneratorDao<K, V extends Serializable> {

	@Resource
	protected StringRedisTemplate stringRedisTemplate;
	
	@Resource
	protected RedisTemplate<K, V> redisTemplate;
	
	public void add(K key, V value) {
		redisTemplate.opsForValue().set(key, value);
	}
	
	public void add(K key, V value, long timeout, TimeUnit unit) {
		redisTemplate.opsForValue().set(key, value, timeout, unit);
	}
	
	public void delete(K key) {
		redisTemplate.delete(key);
	}

	public void delete(List<K> keys) {
		redisTemplate.delete(keys);
	}
	
	public StringRedisTemplate getStringRedisTemplate() {
		return stringRedisTemplate;
	}
	
	public V get(K key) {
		V v = redisTemplate.opsForValue().get(key);
		return v;
	}
	
	public void update(K key, V value) {
		V v = get(key);
		if(null == v) {
			throw new NullPointerException("data not found, key =" + key);
		}
		redisTemplate.opsForValue().set(key, value);
	}
	
	public boolean exists(K key) {
		return redisTemplate.hasKey(key);
	}
	
	public Set<K> getKeyList(K pattern) {
		return redisTemplate.keys(pattern);
	}

	public void setStringRedisTemplate(StringRedisTemplate stringRedisTemplate) {
		this.stringRedisTemplate = stringRedisTemplate;
	}

	public RedisTemplate<K, V> getRedisTemplate() {
		return redisTemplate;
	}

	public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}
	
	protected RedisSerializer<String> getRedisSerializer() {    
        return redisTemplate.getStringSerializer();    
    }    
	
}
